package com.appspot.categoryeditor.controller;

import java.util.List;

import org.codehaus.jackson.JsonParseException;
import org.codehaus.jackson.map.ObjectMapper;
import org.slim3.controller.MultipartRequestHandler;
import org.slim3.controller.Navigation;
import org.slim3.controller.upload.FileItem;

import com.appspot.categoryeditor.exception.EntityPropertySizeLimitException;
import com.appspot.categoryeditor.utils.UrlUtils;

public class JsonUploadController extends AbstractCategoryController {

	@Override
	protected Navigation run() throws Exception {
		
		MultipartRequestHandler handler = new MultipartRequestHandler(request);
		handler.handle();
		FileItem item = requestScope("jsonData");
		
				
		byte[] bytes = item.getData();
		String jsonText = new String(bytes, "UTF-8");
					
		ObjectMapper objectMapper = new ObjectMapper();
		try {
			objectMapper.readValue(jsonText, List.class);
		} catch (JsonParseException e) {
			request.setAttribute("errormessage", 
				"JSONファイルのフォーマットが正しくありません。");
			return forward("/userpage");
		}
		
		getParams();
		getCategoryModel();
		categoryModel.setContent(jsonText);
		try {
			checkContentSize();
		} catch (EntityPropertySizeLimitException e) {
			request.setAttribute("errormessage", 
			"JSONファイルのサイズが制限を超えています。");
			return forward("/userpage");
		}
		putCategory();
		
		return redirect(UrlUtils.createUserPageUrl(userid, categoryid));

	}

}
